A variable is a location in memory (storage area) to hold data.
To indicate the storage area, each variable should be given a unique name (identifier).
A variable is a container which holds the value while the Java program is executed. A variable is assigned with a data type.
Syntax:
datatype variableName;;
Data Types
Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
Primitive Data Types
To store different types of data java provides us different data types.
int
It is used to store whole numbers.
Size 4 bytes
Range ( ±231)
For ex: 4117 , -7463 , 0xA123 , 0277 , 0b01011 etc.
short
To Store whole numbers
Size 2 bytes
Range from -32,768 to 32,767 ( ±215)
For ex: 4117 , -7463 , 0xA123 , 0277 , 0b01011 etc.
long
To Store whole numbers
Size 8 bytes
Range from( ±263)
For ex: 41177437722l , 0x6373C12A123L , 0277L , 0b0101100010101L etc.
Note : long values with suffix l / L
byte
To Store whole numbers
Size 1 byte
Range from -128 to 127( ±27)
For ex : 27 , 0xA3 , 072
float
It is used to store floating point values
Size in memory is 4 bytes
float has 7 decimal digits of precision.
Range (1.2e-38 to 3.4e38 )
For ex: 3.14f , -0.0124f , 2.015fe+003 etc.
Note: float values with suffix f/F
double
It is used to store floating point values.
Size in memory is 8 bytes
double has 15 decimal digits of precision.
Range (2.2e-308 to 1.8e308 )
For ex: 3.140163 , -0.01253424 , 2.015657e+003 etc
Note: double values with suffix d/D By default values with decimal point are of type double if suffix is not specified.
boolen
To store Boolean values i.e. true or false.
Size is 1 bi
For ex: true , false
char
To Store a single character.
Size 8 bytes
Supports UNICODE char set
For ex : ‘A’ , ‘a’ , ‘$’ , ’ ‘ etc.
Identifier
It is a Name which is use to identify different type of programing elements such as Variables , Constants ,Functions….etc
Rule for defining identifier
An identifier must start with alphabets [a to z] [A to Z] or underscore [ _ ].
Next letters of an identifier can be alphabets [a to z] [A to Z], underscore [ _ ] or digits [0 to 9] .
Language keywords are no allowed as identifier.
Max length of identifier can be 31 letters but it can vary depending on different compilers.
No special symbols [eg. #,$..etc] are allowed. Except [_]
Keywords
Java keywords are also known as reserved words. Keywords are particular words that act as a key to a code. These are predefined words by Java so they cannot be used as a variable or object name or class name.